using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Browser;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.CostCenterServices;
using MSIACCSL2.CurrencyServices;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.DeliveryTypeServices;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.ItemServices;
using MSIACCSL2.PalletServices;
using MSIACCSL2.SalesmanServices;
using MSIACCSL2.SpkServices;
using MSIACCSL2.SubGroupServices;
using MSIACCSL2.Views.Spk;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.SpkServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.SpkServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.SpkServices.SaveCompletedEventArgs;


namespace MSIACCSL2.ViewModels
{
    public class SpkViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private static NavigationService _NavigationService;
        private readonly CostCenterServicesClient CostCenterClient;
        private readonly CurrencyServicesClient CurrencyClient;
        private readonly CustomerServicesClient CustomerClient;
        private readonly DeliveryTypeServicesClient DeliveryTypeClient;
        private readonly ItemServicesClient ItemClient;
        private readonly SubGroupServiceClient SubgroupClient;
        private readonly WarehouseServicesClient WarehouseClient;
        private readonly ValidationHandler validationHandler;
        private AplicationStateServicesClient ApplicationService;
        private int CurrentPage;
        public string Expression;
        private InventoryServiceClient InventoryClient;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private PalletServicesClient PalletClient;
        private ObservableCollection<CostCenterDTO> _CostCenters;
        private ObservableCollection<CurrencyDTO> _Currencys;
        private ObservableCollection<CustomerDTO> _Customers;
        private ObservableCollection<DeliveryTypeDTO> _DeliveryTypes;
        private Visibility _GridInventoryVisibility;
        private Visibility _GridItemVisibility;
        private Visibility _GridSubgroupVisibility;
        private bool _IsBusy;
        private bool _IsEnabled;
        private ObservableCollection<ItemDTO> _Items;
        private SpkDTO _Spk;
        private SpkDetailDTO _SpkDetailCurrent;
        private PagedCollectionView _Spks;
        private List<string> _errors;
        private InventoryDTO _inventory;
        private ObservableCollection<ItemDTO> _items;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private ObservableCollection<PalletDTO> _pallets;
        private ObservableCollection<SubGroupDTO> _subgroups;
        private ObservableCollection<WarehouseDTO> _warehouses;
        private SpkServicesClient client;
        private static Search frmSearch;
        private Dictionary<string, object> criteria;
        private string expression;
        private SalesmanServices.SalesmanServicesClient SalesClient;
        private ObservableCollection<EmployeeDTO> _Salesmans;

        public SpkViewModel()
        {
            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            IsEnabled = true;

            if (!DesignerProperties.IsInDesignTool)
            {
                client = new SpkServicesClient();
                CurrencyClient = new CurrencyServicesClient();
                CustomerClient = new CustomerServicesClient();
                DeliveryTypeClient = new DeliveryTypeServicesClient();
                SubgroupClient = new SubGroupServiceClient();
                ItemClient = new ItemServicesClient();
                InventoryClient = new InventoryServiceClient();
                WarehouseClient = new WarehouseServicesClient();
                PalletClient = new PalletServicesClient();
                CostCenterClient = new CostCenterServicesClient();
                ApplicationService = new AplicationStateServicesClient();
                SalesClient = new SalesmanServicesClient();

                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveSpk, CanSave);
                New = new DelegateCommand(NewSpk, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchSpk, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                GetRateCommand = new DelegateCommand(GetRate, CanGetRateCommand);
                SubGroupCommand = new DelegateCommand(EntrySubGroup, CanSubgroupCommand);
                ItemCommand = new DelegateCommand(EntryItem, CanItemCommand);
                InventoryCommand = new DelegateCommand(EntryInventory, CanInventoryCommand);
                GetSubGroupCommand = new DelegateCommand(GetSubgroupByName, CanGetSubgroupCommand);

                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                GridSubgroupVisibility = Visibility.Collapsed;
                GridItemVisibility = Visibility.Collapsed;
                GridInventoryVisibility = Visibility.Collapsed;

                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    Spk = new SpkDTO();
                    Spk.SPKDate = null;
                    GetCurrencyList();
                    GetDeliveryTypeList();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public ObservableCollection<CostCenterDTO> CostCenters
        {
            get { return _CostCenters; }
            private set
            {
                if (CostCenters == value) return;
                _CostCenters = value;
                FirePropertyChanged("CostCenters");
            }
        }

        public PagedCollectionView Spks
        {
            get { return _Spks; }

            private set
            {
                if (Spks == value) return;
                _Spks = value;
                int i = (CurrentPage*30);
                foreach (object Spk in Spks)
                {
                    i += 1;

                    ((SpkDTO) Spk).No = i;
                }
                FirePropertyChanged("Spks");
                Spks.CollectionChanged += Spk_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<CurrencyDTO> Currencys
        {
            get { return _Currencys; }
            private set
            {
                if (Currencys == value) return;
                _Currencys = value;
                FirePropertyChanged("Currencys");
            }
        }


        public ObservableCollection<CustomerDTO> Customers
        {
            get { return _Customers; }
            private set
            {
                if (Customers == value) return;
                _Customers = value;
                FirePropertyChanged("Customers");
            }
        }


        public ObservableCollection<DeliveryTypeDTO> DeliveryTypes
        {
            get { return _DeliveryTypes; }
            private set
            {
                if (DeliveryTypes == value) return;
                _DeliveryTypes = value;
                FirePropertyChanged("DeliveryTypes");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public SpkDTO Spk
        {
            get { return _Spk; }
            private set
            {
                if (Spk == value) return;
                _Spk = value;
                FirePropertyChanged("Spk");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public Visibility GridItemVisibility
        {
            get { return _GridItemVisibility; }
            private set
            {
                if (GridItemVisibility == value) return;
                _GridItemVisibility = value;
                FirePropertyChanged("GridItemVisibility");
            }
        }

        public Visibility GridSubgroupVisibility
        {
            get { return _GridSubgroupVisibility; }
            private set
            {
                if (GridSubgroupVisibility == value) return;
                _GridSubgroupVisibility = value;
                FirePropertyChanged("GridSubgroupVisibility");
            }
        }

        public Visibility GridInventoryVisibility
        {
            get { return _GridInventoryVisibility; }
            private set
            {
                if (GridInventoryVisibility == value) return;
                _GridInventoryVisibility = value;
                FirePropertyChanged("GridInventoryVisibility");
            }
        }

        public ObservableCollection<SubGroupDTO> Subgroups
        {
            get { return _subgroups; }
            private set
            {
                if (Subgroups == value) return;
                _subgroups = value;
                FirePropertyChanged("Subgroups");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }

        public ObservableCollection<EmployeeDTO> Salesmans
        {
            get { return _Salesmans; }
            private set
            {
                if (Salesmans == value) return;
                _Salesmans = value;
                FirePropertyChanged("Salesmans");
            }
        }

        public SpkDetailDTO SpkDetailCurrent
        {
            get { return _SpkDetailCurrent; }
            private set
            {
                if (SpkDetailCurrent == value) return;
                _SpkDetailCurrent = value;
                FirePropertyChanged("SpkDetailCurrent");
            }
        }

        public ObservableCollection<ItemDTO> Items
        {
            get { return _Items; }
            set
            {
                if (Items == value) return;
                _Items = value;
                FirePropertyChanged("Items");
            }
        }

        public ICommand GetRateCommand { get; set; }
        public ICommand LoadPreSalesCommand { get; set; }
        public ICommand GetSubGroupCommand { get; set; }
        public ICommand SubGroupCommand { get; set; }
        public ICommand ItemCommand { get; set; }
        public ICommand InventoryCommand { get; set; }

        private void PrepareEdit()
        {
            Spk = (SpkDTO) Navigation.Args;
            GetSpk(Spk);
            CekTransaksi();
        }


        private void PrepareAdd()
        {
            GetCurrencyList();
            GetDeliveryTypeList();
            GetCostCenterList();
            //GetLastNoSpk();
            GetSalesmanList(Mode.Add);

            Spk = new SpkDTO();
            Spk.SpkDetails = new ObservableCollection<SpkDetailDTO>();
            var SpkDetail = new SpkDetailDTO();
            Spk.SpkDetails.Add(SpkDetail);
            //CekTransaksi();

            GridInventoryVisibility = Visibility.Collapsed;
            GridItemVisibility = Visibility.Collapsed;
            GridSubgroupVisibility = Visibility.Collapsed;
        }

        private void GetSpk(SpkDTO SpkDto)
        {
            IsBusy = true;
            client.GetSpkCompleted += client_GetSpkCompleted;
            client.GetSpkAsync(SpkDto.NoSPK);
        }

        private void client_GetSpkCompleted(object sender, GetSpkCompletedEventArgs e)
        {
            client.GetSpkCompleted -= client_GetSpkCompleted;
            Spk = e.Result;
            if (Spk.Status == Status.Void || Spk.Status == Status.Close) IsEnabled = false;
            if (Spk.SpkDetails == null)
                Spk.SpkDetails = new ObservableCollection<SpkDetailDTO>();
            if (Spk.SpkDetails.Count == 0)
                Spk.SpkDetails.Add(new SpkDetailDTO());

            if (Spk.Type.ToLower() == "subgroup")
            {
                GetSubGroupList(Mode.Edit);
                GridSubgroupVisibility = Visibility.Visible;
            }
            else if (Spk.Type.ToLower() == "item")
            {
                GetItemList(Mode.Edit);
                GridItemVisibility = Visibility.Visible;
            }
            else
            {
                GridInventoryVisibility = Visibility.Visible;
            }

            GetCurrencyList();
            GetDeliveryTypeList();
            GetCostCenterList();
            GetSalesmanList(Mode.Edit);
            IsBusy = false;
        }

        private void GetCostCenterList()
        {
            CostCenterClient.GetAllCostCenterCompleted += CostCenterClient_GetAllCostCenterCompleted;
            CostCenterClient.GetAllCostCenterAsync();
        }

        private void CostCenterClient_GetAllCostCenterCompleted(object sender, GetAllCostCenterCompletedEventArgs e)
        {
            CostCenterClient.GetAllCostCenterCompleted -= CostCenterClient_GetAllCostCenterCompleted;
            CostCenters = e.Result;
        }


        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void Spk_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveSpk(Object spk)
        {
            if (Spk.SpkDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (Spk.SpkDetails[0].SubGroup == null &&
                    Spk.SpkDetails[0].Item == null &&
                    Spk.SpkDetails[0].Inventory == null)
                    Spk.SpkDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            Spk.created_by = GlobalVar.User.UserID;
            Spk.modified_by = GlobalVar.User.UserID;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(Spk, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode)e.UserState;
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }else
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/Spk/Index", UriKind.Relative));
            }
         
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            Spks = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewSpk(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/Spk/FrmAdd", UriKind.Relative));
        }


        private void SearchSpk(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in Spk.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(Spk, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(Spk, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(Spk, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(Spk, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(Spk, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(Spk, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(Spk, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(Spk, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(Spk, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(Spk, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            SpkSearch(criteria, expression,1);
        }

        private void SpkSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            if (criteria.ContainsKey("Status")) criteria.Remove("Status");
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            Spks = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }


        private void GetCurrencyList()
        {
            CurrencyClient.GetAllCurrencyCompleted += CurrencyClient_GetAllCurrencyCompleted;
            CurrencyClient.GetAllCurrencyAsync();
        }

        private void CurrencyClient_GetAllCurrencyCompleted(object sender, GetAllCurrencyCompletedEventArgs e)
        {
            CurrencyClient.GetAllCurrencyCompleted -= CurrencyClient_GetAllCurrencyCompleted;
            Currencys = e.Result;
            Spk.Currency = Currencys.FirstOrDefault(x => x.CurrencyCode == "Rp");
            Spk.Rate = Spk.Currency.Kurs;

            if (Spk != null)
            {
                if (Spk.Currency == null) return;
                Spk.Currency =
                    Currencys.FirstOrDefault(s => s.CurrencyCode == Spk.Currency.CurrencyCode);
            }
        }

        private void GetDeliveryTypeList()
        {
            DeliveryTypeClient.GetAllDeliveryTypeCompleted += DeliveryTypeClient_GetAllDeliveryTypeCompleted;
            DeliveryTypeClient.GetAllDeliveryTypeAsync();
        }

        private void DeliveryTypeClient_GetAllDeliveryTypeCompleted(object sender,
                                                                    GetAllDeliveryTypeCompletedEventArgs e)
        {
            DeliveryTypeClient.GetAllDeliveryTypeCompleted -= DeliveryTypeClient_GetAllDeliveryTypeCompleted;
            DeliveryTypes = e.Result;

            if (Spk != null)
            {
                if (Spk.DeliveryType == null) return;
                Spk.DeliveryType =
                    DeliveryTypes.FirstOrDefault(s => s.DeliveryCode == Spk.DeliveryType.DeliveryCode);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            Spk = null;
            if (Spks != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    SpkSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }

        public bool CanSave(Object param)
        {
            return true;
        }

        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }

        public bool CanUnload(Object param)
        {
            return true;
        }

        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }

        public bool CanGetSubgroupCommand(Object param)
        {
            return true;
        }

        public void Release(Object param)
        {
            param = null;
            Spk = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (Spks == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            //if (string.IsNullOrEmpty(Spk.NoSPK))
            //    Errors.Add("Nomor SPK tidak boleh kosong");
            if (Spk.Salesman == null)
                Errors.Add("Salesman tidak boleh kosong!");
            if (Spk.Currency == null)
                Errors.Add("Currency tidak boleh kosong!");
            if (Spk.Type == null)
                Errors.Add(" Sales Order Type tidak boleh kosong!");
            if (Spk.SpkDetails.Count < 1)
                Errors.Add("Spk Detail harus diisi!");
            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
                MessageVisibility = Visibility.Visible;
            else
                MessageVisibility = Visibility.Collapsed;
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        public void GetLastNoSpk()
        {
            client = new SpkServicesClient();
            client.GetLastNoSPKCompleted += client_GetLastNoSPKCompleted;
            client.GetLastNoSPKAsync();
        }

        private void client_GetLastNoSPKCompleted(object sender, GetLastNoSPKCompletedEventArgs e)
        {
            client.GetLastNoSPKCompleted -= client_GetLastNoSPKCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO = string.Empty;

            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }

            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);

            Spk.NoSPK = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }


        public bool CanGetRateCommand(Object param)
        {
            return true;
        }

        public void GetRate(Object param)
        {
            if (Spk == null) return;
            CurrencyClient.GetCurrencyCompleted += CurrencyClient_GetCurrencyCompleted;
            CurrencyClient.GetCurrencyAsync(Spk.Currency.CurrencyCode);
        }

        private void CurrencyClient_GetCurrencyCompleted(object sender, GetCurrencyCompletedEventArgs e)
        {
            CurrencyClient.GetCurrencyCompleted -= CurrencyClient_GetCurrencyCompleted;
            Spk.Rate = e.Result.Kurs;
        }

        public bool CanLoadPreSalesCommand(Object param)
        {
            return true;
        }


        public void GetSubGroupList(Mode mode)
        {
            SubgroupClient.GetAllSubGroupCompleted += SubgroupClient_GetAllSubGroupCompleted;
            SubgroupClient.GetAllSubGroupAsync(mode);
        }

        private void SubgroupClient_GetAllSubGroupCompleted(object sender, GetAllSubGroupCompletedEventArgs e)
        {
            SubgroupClient.GetAllSubGroupCompleted -= SubgroupClient_GetAllSubGroupCompleted;
            var Subgroups = new ObservableCollection<SubGroupDTO>((from s in e.Result
                                                                   select
                                                                       new SubGroupDTO
                                                                           {
                                                                               SubGroupID = s.SubGroupID,
                                                                               SubGroupName = s.SubGroupName
                                                                           }));
            if (((Mode) e.UserState) == Mode.Edit || ((Mode) e.UserState) == Mode.Add)
                foreach (SpkDetailDTO orderDetail in Spk.SpkDetails)
                {
                    if (orderDetail.SubGroup != null)
                    {
                        orderDetail.Subgroups = Subgroups;
                        orderDetail.SubGroup =
                            Subgroups.FirstOrDefault(s => s.SubGroupID == orderDetail.SubGroup.SubGroupID);
                    }
                }
        }

        public void GetItemList(Mode mode)
        {
            if (mode == Mode.Edit || mode == Mode.Add)
                foreach (SpkDetailDTO orderDetail in Spk.SpkDetails)
                {
                    if (orderDetail.Item != null)
                    {
                        orderDetail.Items = new ObservableCollection<ItemDTO>();
                        orderDetail.Items.Add(orderDetail.Item);
                        orderDetail.Item =
                            orderDetail.Items.FirstOrDefault(s => s.ItemId == orderDetail.Item.ItemId);
                    }
                }
            EventAggregator.PublishMessage("Refresh", this);
        }


        public void GetSalesmanList(Mode mode)
        {
            SalesClient.GetAllSalesmanCompleted += new EventHandler<GetAllSalesmanCompletedEventArgs>(SalesClient_GetAllSalesmanCompleted);
            SalesClient.GetAllSalesmanAsync(mode);
        }

        void SalesClient_GetAllSalesmanCompleted(object sender, GetAllSalesmanCompletedEventArgs e)
        {
            SalesClient.GetAllSalesmanCompleted -= new EventHandler<GetAllSalesmanCompletedEventArgs>(SalesClient_GetAllSalesmanCompleted);
            Salesmans = e.Result;
            var Mode = (Mode) e.UserState;
            if (Mode==Mode.Edit)
            {
                if (Spk.Salesman != null)
                    Spk.Salesman = Salesmans.FirstOrDefault(x => x.KodeSalesman == Spk.Salesman.KodeSalesman);

            }

        }


        public bool CanSubgroupCommand(Object param)
        {
            return true;
        }

        public bool CanItemCommand(Object param)
        {
            return true;
        }

        public bool CanInventoryCommand(Object param)
        {
            return true;
        }

        public void EntrySubGroup(Object param)
        {
            if (Spk.SpkDetails[0].Inventory != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].Inventory.SerialNumber))
                return;
            if (Spk.SpkDetails[0].Item != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].Item.ItemName))
                return;
            if (Spk.SpkDetails[0].SubGroup == null)
                Spk.SpkDetails[0].SubGroup = new SubGroupDTO();

            ((SpkDTO) param).Type = "SubGroup";
            GridSubgroupVisibility = Visibility.Visible;
            GridItemVisibility = Visibility.Collapsed;
            GridInventoryVisibility = Visibility.Collapsed;
        }

        public void EntryItem(Object param)
        {
            if (Spk.SpkDetails[0].Inventory != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].Inventory.SerialNumber))
                return;
            if (Spk.SpkDetails[0].SubGroup != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].SubGroup.SubGroupName))
                return;
            if (Spk.SpkDetails[0].Item == null)
                Spk.SpkDetails[0].Item = new ItemDTO(); 

            ((SpkDTO) param).Type = "Item";
            GridItemVisibility = Visibility.Visible;
            GridSubgroupVisibility = Visibility.Collapsed;
            GridInventoryVisibility = Visibility.Collapsed;
        }

        public void EntryInventory(Object param)
        {
            if (Spk.SpkDetails[0].Item != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].Item.ItemName))
                return;
            if (Spk.SpkDetails[0].SubGroup != null && !string.IsNullOrEmpty(Spk.SpkDetails[0].SubGroup.SubGroupName))
                return;
            if (Spk.SpkDetails[0].Inventory == null)
                Spk.SpkDetails[0].Inventory = new InventoryDTO();

            ((SpkDTO) param).Type = "Inventory";
            GridInventoryVisibility = Visibility.Visible;
            GridSubgroupVisibility = Visibility.Collapsed;
            GridItemVisibility = Visibility.Collapsed;
        }

        public void GetSubgroupByName(Object param)
        {
            if (param.GetType() == typeof (SpkDetailDTO))
            {
                SpkDetailCurrent = (SpkDetailDTO) param;
                SubgroupClient.GetSubGroupListByNameCompleted += SubgroupClient_GetSubGroupListByNameCompleted;
                SubgroupClient.GetSubGroupListByNameAsync(SpkDetailCurrent.SubGroup.SubGroupName);
            }
            else
            {
                SubgroupClient.GetSubGroupListByNameCompleted += SubgroupClient2_GetSubGroupListByNameCompleted;
                SubgroupClient.GetSubGroupListByNameAsync(param.ToString());
            }
        }

        private void SubgroupClient_GetSubGroupListByNameCompleted(object sender,
                                                                   GetSubGroupListByNameCompletedEventArgs e)
        {
            SubgroupClient.GetSubGroupListByNameCompleted -= SubgroupClient_GetSubGroupListByNameCompleted;
            Subgroups = e.Result;
        }

        public void GetItemByName(Object param)
        {
            if (param.GetType() == typeof (SpkDetailDTO))
            {
                SpkDetailCurrent = (SpkDetailDTO) param;
                ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
                ItemClient.GetItemByNameAsync(SpkDetailCurrent.Item.ItemName);
            }
            else
            {
                ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
                ItemClient.GetItemByNameAsync(param.ToString());
            }
        }

        private void ItemClient_GetItemByNameCompleted(object sender, GetItemByNameCompletedEventArgs e)
        {
            ItemClient.GetItemByNameCompleted -= ItemClient_GetItemByNameCompleted;
            Items = e.Result;
        }

        private void SubgroupClient2_GetSubGroupListByNameCompleted(object sender,
                                                                    GetSubGroupListByNameCompletedEventArgs e)
        {
            SubgroupClient.GetSubGroupListByNameCompleted -= SubgroupClient2_GetSubGroupListByNameCompleted;
            Subgroups = e.Result;
        }

        public void Print(Object param)
        {
            Navigation.MyNavigation.Navigate(new Uri("/Spk/PrintPreviewSPK", UriKind.Relative));
            Navigation.Args = param;
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(Spk.NoSPK))
            {
                ApplicationService.IsTransactionUsedAsync(Spk.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = Spk.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(Spk.NoSPK, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = Spk.NoSPK;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/Spk/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(Spk.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(Spk.NoSPK, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as SpkDTO, (x as WarehouseDTO).EmailFolder);
            });
           
        }

        private void client_SendEmailCompleted(object sender, SpkServices.SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }
    }


    public class SpkWrapViewModel : ViewModelBase
    {
        private readonly InventoryServiceClient InventoryClient;
        private readonly SpkServicesClient client;
        private ItemServicesClient ItemClient;
        private SubGroupServiceClient SubGroupClient;
        private List<string> _DiscTypes;
        private SpkDetailDTO _SpkDetail;
        private ObservableCollection<SubGroupDTO> _SubGroups;

        public SpkWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);

                client = new SpkServicesClient();
                InventoryClient = new InventoryServiceClient();
                ItemClient = new ItemServicesClient();
                SubGroupClient = new SubGroupServiceClient();


                AddDetailCommand = new DelegateCommand(AddSpkDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteSpkDetail, CanDeleteDetailCommand);
                GetTotalDetailCommand = new DelegateCommand(GetTotalDetail, CanGetTotalDetailCommand);
                GetPpnCommand = new DelegateCommand(GetPpn, CanGetPpnCommand);
                GetTotalDiscountCommand = new DelegateCommand(GetTotalDiscount, CanGetTotalDiscount);
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);

                DiscTypes = new List<string>();
                DiscTypes.Add("%");
                DiscTypes.Add("val");

                if (SpkViewModel.mode == Mode.Add || SpkViewModel.mode == Mode.Edit)
                {
                }
            }
        }

        public SpkViewModel SpkViewModel { get; set; }

        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }
        public ICommand SearchItemCommand { get; set; }
        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }
        public ICommand GetTotalDetailCommand { get; set; }
        public ICommand GetPpnCommand { get; set; }
        public ICommand GetTotalDiscountCommand { get; set; }

        public SpkDetailDTO SpkDetail
        {
            get { return _SpkDetail; }
            private set
            {
                if (SpkDetail == value) return;
                _SpkDetail = value;
                FirePropertyChanged("SpkDetail");
            }
        }

        public List<string> DiscTypes
        {
            get { return _DiscTypes; }
            private set
            {
                if (DiscTypes == value) return;
                _DiscTypes = value;
                FirePropertyChanged("DiscTypes");
            }
        }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }

        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public bool CanGetTotalDetailCommand(Object param)
        {
            return true;
        }

        public bool CanGetPpnCommand(Object param)
        {
            return true;
        }

        private bool CanSearchItemCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            SpkViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/Spk/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((SpkDTO)param);
            });

        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            SpkViewModel.mode = Mode.Idle;
            var VM = new SpkViewModel();
        }


        public void AddSpkDetail(Object param)
        {
            //SpkDetail.SubGroup = new SubGroupDTO();
            //SpkDetail.Subgroups = SpkViewModel.Spk.SpkDetails[0].Subgroups;
            SpkDetail = new SpkDetailDTO();
            if (SpkViewModel.Spk.Type == "Inventory")
            {
                SpkDetail.Inventory = new InventoryDTO();
                SpkViewModel.Spk.SpkDetails.Add(SpkDetail);
            }
            else if (SpkViewModel.Spk.Type == "Item")
            {
                SpkDetail.Item = new ItemDTO();
                SpkViewModel.Spk.SpkDetails.Add(SpkDetail);
                EventAggregator.PublishMessage("SetFocusFirstColumnItem", this);
            }
            else
            {
                SpkDetail.SubGroup = new SubGroupDTO();
                SpkViewModel.Spk.SpkDetails.Add(SpkDetail);
                EventAggregator.PublishMessage("SetFocusFirstColumnSubgroup", this);
            }
        }

        public void DeleteSpkDetail(Object param)
        {
            var SpkDetail = (SpkDetailDTO) param;
            if (SpkViewModel.Spk.SpkDetails.Count > 1)
            {
                //Jika paramnya null hapus yg terakhir
                if (SpkDetail == null)
                {
                    SpkViewModel.Spk.SpkDetails.RemoveAt(SpkViewModel.Spk.SpkDetails.Count - 1);
                    return;
                }
                if (SpkViewModel != null) SpkViewModel.Spk.SpkDetails.Remove(SpkDetail);
            }
        }

        public void GetTotalDetail(Object param)
        {
            if (param == null) return;
            SpkDetail = (SpkDetailDTO) param;

            Decimal Qty = 0;
            Qty = SpkDetail.Qty;

            if (SpkDetail.DiscountType != "%")
                SpkDetail.TotalDetail = (Qty*SpkDetail.Price) - SpkDetail.Discount;
            else
                SpkDetail.TotalDetail = Qty*
                                        (SpkDetail.Price -
                                         ((SpkDetail.Price)*SpkDetail.Discount/100));
            if (SpkViewModel != null)
            {
                SpkViewModel.Spk.SubTotal =
                    SpkViewModel.Spk.SpkDetails.Sum(p => p.TotalDetail);
                if (SpkViewModel.Spk.DiscountType != "%")
                    SpkViewModel.Spk.AfterDiscount = SpkViewModel.Spk.SubTotal -
                                                     SpkViewModel.Spk.Discount;
                else
                    SpkViewModel.Spk.AfterDiscount = SpkViewModel.Spk.SubTotal -
                                                     (SpkViewModel.Spk.SubTotal*
                                                      SpkViewModel.Spk.Discount/100);
                if (SpkViewModel.Spk.IsPpn)
                    SpkViewModel.Spk.Ppn = SpkViewModel.Spk.AfterDiscount*10/100;
                if (SpkViewModel.Spk.Ppn > 0)
                    SpkViewModel.Spk.IsPpn = true;
                SpkViewModel.Spk.Total =
                    SpkViewModel.Spk.AfterDiscount + SpkViewModel.Spk.Ppn;
            }
        }

        public void GetPpn(Object param)
        {
            var Spk = (SpkDTO) param;
            if (Spk.IsPpn)
            {
                Spk.Ppn = Spk.AfterDiscount*10/100;
                Spk.Total = Spk.AfterDiscount + Spk.Ppn;
            }
            else
            {
                Spk.Ppn = 0;
                Spk.Total = Spk.AfterDiscount + Spk.Ppn;
            }
        }

        public bool CanGetTotalDiscount(Object param)
        {
            return true;
        }

        public void GetTotalDiscount(Object param)
        {
            var Spk = (SpkDTO) param;
            if (Spk.SpkDetails != null)
                Spk.SubTotal =
                    Spk.SpkDetails.Sum(p => p.TotalDetail);
            if (Spk.DiscountType != "%")
                Spk.AfterDiscount = Spk.SubTotal - Spk.Discount;
            else
                Spk.AfterDiscount = Spk.SubTotal - (Spk.SubTotal*Spk.Discount/100);
            if (Spk.IsPpn)
                Spk.Ppn = Spk.AfterDiscount*10/100;
            if (Spk.Ppn > 0)
                Spk.IsPpn = true;
            Spk.Total =
                Spk.AfterDiscount + Spk.Ppn;
        }


        public void GetInventory(Object param)
        {
            SpkDetail = (SpkDetailDTO) param;
            if (SpkDetail.Inventory == null) SpkDetail.Inventory = new InventoryDTO();
            string SerialNumber = SpkDetail.Inventory.SerialNumber;
            //if (SpkViewModel.Spk.SpkDetails.Count >1 && SpkViewModel.Spk.SpkDetails.Any(x => x.Inventory.SerialNumber == SerialNumber)) return;
            //;
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            InventoryClient.GetInventoryAsync(SerialNumber);
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryClient.GetInventoryCompleted -=
                InventoryClient_GetInventoryCompleted;
            InventoryDTO InventoryTemp = e.Result;

            if (null != InventoryTemp)
            {
                if (string.IsNullOrEmpty(InventoryTemp.SerialNumber)) MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
                SpkDetail.Inventory = InventoryTemp;
                SpkDetail.Inventory.Item =
                    e.Result.Item;
                SpkDetail.Inventory.SatuanUnit =
                    e.Result.SatuanUnit;
                SpkDetail.Panjang = e.Result.Panjang;
                SpkDetail.Lebar = e.Result.Lebar;
                SpkDetail.Tinggi = e.Result.Tinggi;
                SpkDetail.Qty = e.Result.QtyUnit;
            }
        }

        public void GetQtyUnit(Object param)
        {
            SpkDetail = param as SpkDetailDTO;
            if (SpkDetail.Inventory != null)
                if (SpkDetail.Inventory.SatuanUnit != null)
                {
                    SpkDetail.Qty = SpkDetail.Inventory.QtyPack*
                                    (SpkDetail.Panjang*
                                     SpkDetail.Lebar*
                                     SpkDetail.Tinggi)/
                                    SpkDetail.Inventory.SatuanUnit.Pengali;
                    GetTotalDetail(SpkDetail);
                }
        }
    }


    public class SpkConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).NoSPK;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}